package com.wdciti.sccp.iot.springvertx;

import com.wdciti.sccp.iot.common.aio.AioEngine;
import com.wdciti.sccp.iot.common.aio.DeploymentResult;
import com.wdciti.sccp.iot.common.aio.HandlerDeploy;
import com.wdciti.sccp.iot.springvertx.configure.VertxOptionsConfiguration;
import com.wdciti.sccp.iot.springvertx.factory.AbstractVerticleFactory;
import io.vertx.core.Vertx;
import io.vertx.core.spi.VerticleFactory;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by early
 */
@Slf4j
public class VertxInSpring implements AioEngine, ApplicationContextAware {

    @Getter
    VertxOptionsConfiguration vertxOptionsConfiguration;

    @Getter
    private Vertx vertx;
    private ApplicationContext context;
    private boolean running = false;

    public VertxInSpring(VertxOptionsConfiguration configuration) {
        this.vertxOptionsConfiguration = configuration;
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @PostConstruct
    @Override
    public void initialize() {
        this.vertx = Vertx.vertx(vertxOptionsConfiguration);
        log.info("[[[[[[...start Vertx .............]]]]]]");
//        vertx.sharedData().getAsyncMap("conf").onSuccess(obj->obj.put("aa","bb"));   //TODO: for TEST
        Map<String, VerticleFactory> factories = context.getBeansOfType(VerticleFactory.class);
        factories.forEach((k, v) -> vertx.registerVerticleFactory(v));
//        try {
//            doDeploying();
//        } catch (DeployingException e) {
//            log.error(e.getMessage());
//        }
//        running = true;
    }

    @Override
    public void doDeploying() {
        Map<String, HandlerDeploy> factories = context.getBeansOfType(HandlerDeploy.class);
        factories.forEach((k, v) -> v.prepare().deploy());
        running = true;
    }

    @Override
    public void destroy() {
        this.vertx.close();
    }

    @Override
    public Map<String, DeploymentResult> getDeployResults() {
        Map<String, AbstractVerticleFactory> factories = context.getBeansOfType(AbstractVerticleFactory.class);
        Map<String, DeploymentResult> map = new HashMap<>(factories.size());
        factories.forEach((k, v) -> map.put(k, v.getResult()));
        return map;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        this.context = context;
    }

}
